package com.yylending.las.lending;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import com.tbruyelle.rxpermissions.Permission;
import com.yyfax.common.CLog;
import com.yyfax.infrastructure.PermissionsGrantedHelper;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.statistics.StatService;
import com.yylending.las.Constants;
import com.yylending.las.Global;
import com.yylending.las.R;
import com.yylending.las.StatIDSet;
import com.yylending.las.base.BaseFragment;
import com.yylending.las.common.utils.FormatUtils;
import com.yylending.las.common.widgets.CommonDialog;
import com.yylending.las.common.widgets.RedDotView;
import com.yylending.las.common.widgets.TelephoneTextView;
import com.yylending.las.lending.quota.myquota.MyQuotaModel;
import com.yylending.las.lending.video.VideoVerifyActivity;
import com.yylending.las.main.MainController;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

/**
 * 借钱申请提交后的状态:不需要现调
 * Created by ying_he on 2017/6/23.<br>
 * Copyright  2017 www.yylending.com. All Rights Reserved.<br><br>
 */
public class NoSiteInvestigationLendingFragment extends BaseFragment {

	static final String TAG = NoSiteInvestigationLendingFragment.class.getSimpleName();
	static final String ARG_APPLY_STATUS = "arg_apply_status";
	static final String ARG_AUTO_TIPS = "arg_auto_tips";

	Unbinder unbinder;
	@BindView(R.id.title_left_iv)
	ImageView mTitleLeftIv;
	@BindView(R.id.title_tv)
	TextView mTitleTv;
	@BindView(R.id.title_right_tv)
	TextView mTitleRightTv;
	@BindView(R.id.title_right_iv)
	ImageView mTitleRightIv;
	@BindView(R.id.layout_title_bar)
	RelativeLayout mLayoutTitleBar;
	@BindView(R.id.tel_confirm_tv)
	TextView mTelConfirmTv;
	@BindView(R.id.video_confirm_tv)
	TextView mVideoConfirmTv;
	@BindView(R.id.lending_review_tv)
	TextView mLendingReviewTv;
	@BindView(R.id.loan_sum_tv)
	TextView mLoanSumTv;
	@BindView(R.id.lending_notice_tv)
	TextView mLendingNoticeTv;
	@BindView(R.id.service_phone_tv)
	TelephoneTextView mServicePhoneTv;
	@BindView(R.id.loan_btn)
	Button mLoanBtn;
	@BindView(R.id.red_dot_view)
	RedDotView mRedDotView;
	@BindView(R.id.tel_confirm_iv)
	ImageView mTelConfirmIv;
	@BindView(R.id.lending_review_iv)
	ImageView mLendingReviewIv;
	@BindView(R.id.tel_confirm_complete_iv)
	ImageView mTelConfirmCompleteIv;
	@BindView(R.id.lending_review_complete_iv)
	ImageView mLendingReviewCompleteIv;
	@BindView(R.id.video_confirm_hint_iv)
	ImageView mVideoConfirmHintIv;

	MyQuotaModel.ApplyStatus mApplyStatus;
	boolean mAutoTips = false;

	private boolean mGrantedCamera = false;
	private boolean mGrantedMicrophone = false;
	private boolean mAutoJump = false;

	public static BaseFragment newInstance(MyQuotaModel.ApplyStatus status, boolean autoTips) {
		BaseFragment fragment = new NoSiteInvestigationLendingFragment();
		Bundle args = new Bundle();
		args.putParcelable(ARG_APPLY_STATUS, status);
		args.putBoolean(ARG_AUTO_TIPS, autoTips);
		fragment.setArguments(args);
		return fragment;
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		return null;
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		unbinder.unbind();
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_no_site_investigation_lending, container, false);
		unbinder = ButterKnife.bind(this, view);
		initView();
		return view;
	}

	@Override
	public void onStart() {
		super.onStart();
		if(mAutoJump){
			if(mGrantedCamera && mGrantedMicrophone) {
				goToVideoVerify();
			}else{
				if(Global.isThirdPartyPageOpened()){
					applyPermission();
				}
			}
		}
		Global.setThirdPartyPageOpenedFlag(false);
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	private void initView() {
		mApplyStatus = getArguments().getParcelable(ARG_APPLY_STATUS);
		mAutoTips = getArguments().getBoolean(ARG_AUTO_TIPS, false);
		mLoanSumTv.setText(FormatUtils.getDecoratedAmount(mApplyStatus.loanAmount));
		mTitleTv.setTextColor(ContextCompat.getColor(getActivity(), R.color.color_333333));
		mTitleTv.setText(R.string.tab_lend);
		mLayoutTitleBar.setBackgroundResource(0);
		mLayoutTitleBar.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.color_white));
		mTitleLeftIv.setImageResource(R.drawable.ic_help_black);
		mTitleRightIv.setImageResource(R.drawable.ic_message_black);
		mServicePhoneTv.setPageNo(Constants.PAGE_NO_MAIN_ACTIVITY);
		switch (mApplyStatus.loanState) {
			case Constants.LOAN_STATUS_ING:
				//前两个按钮亮
				updateBtnState(mApplyStatus.loanState);
				mLoanBtn.setEnabled(false);
				mLoanBtn.setText(R.string.wait_phone_confirm);
				StatService.onEvent(getContext(), StatIDSet.EVENT_ID_TELEPHONE_INQUIRY);
				break;
			case Constants.LOAN_STATUS_VIDEO_AUTH:
				//第一个亮，默认，按钮可点击
				mLoanBtn.setEnabled(true);
				mLoanBtn.setText(R.string.video_authentication);
				break;
			case Constants.LOAN_STATUS_REVIEW:
			case Constants.LOAN_WAIT_FOR_LOANING:
				//按钮全亮，按钮不可点击
				updateBtnState(mApplyStatus.loanState);
				mLoanBtn.setEnabled(false);
				if (Constants.LOAN_WAIT_FOR_LOANING.equals(mApplyStatus.loanState)) {
					mLoanBtn.setText(R.string.in_loan);
				} else {
					mLoanBtn.setText(R.string.in_review);
				}
				StatService.onEvent(getContext(), StatIDSet.EVENT_ID_BREWED_IN_THE_AUDIT);
				break;
		}
		MainController.initRedDot(mRedDotView);
		if (mAutoTips) {
			showOneBtnDialog(getString(R.string.video_verify_hint), getString(R.string.got_it));
		}
	}

	/**
	 * 更新按钮状态
	 */
	private void updateBtnState(String loanState) {
		mTelConfirmIv.setImageResource(R.drawable.ic_tel_confirm);
		mTelConfirmTv.setTextColor(getActivity().getResources().getColor(R.color.color_333333));
		mTelConfirmCompleteIv.setImageResource(R.drawable.ic_blue_dot_divider);
		if (Constants.LOAN_STATUS_REVIEW.equals(loanState) || Constants.LOAN_WAIT_FOR_LOANING.equals(loanState)) {
			mLendingReviewIv.setImageResource(R.drawable.ic_lending_review);
			mLendingReviewTv.setTextColor(getActivity().getResources().getColor(R.color.color_333333));
			mLendingReviewCompleteIv.setImageResource(R.drawable.ic_blue_dot_divider);
		}
	}

	private void goToVideoVerify(){
		mAutoJump = false;
		if (notWorkTime()) {
			showOneBtnDialog(R.string.video_verify_not_work_time, R.string.confirm);
		} else {
			StatService.onEvent(getContext(), StatIDSet.EVENT_ID_START_VIDEO_AUTHENTICATION);
			VideoVerifyActivity.start(getActivity(), mApplyStatus.loanAmount);
		}
	}

	@OnClick({R.id.loan_btn, R.id.lending_notice_tv, R.id.title_left_iv, R.id.title_right_iv, R.id.video_confirm_hint_iv})
	public void onClick(View view) {
		switch (view.getId()) {
			case R.id.loan_btn:
				if(mGrantedCamera && mGrantedMicrophone){
					goToVideoVerify();
				}else{
					mAutoJump = true;
					applyPermission();
				}
				break;
			case R.id.lending_notice_tv:
				EventAgent.post(new QuotaEvent.ShowLoanNoticeEvent(QuotaEvent.ShowLoanNoticeEvent.QUOTA_SHOW_LOAN_NOTICE, Constants.PAGE_NO_MAIN_ACTIVITY));
				break;
			case R.id.title_left_iv:
				EventAgent.post(new QuotaEvent.PageJumpEvent(QuotaEvent.PageJumpEvent.QUOTA_JUMP_HELP_PAGE, Constants.PAGE_NO_MAIN_ACTIVITY));
				break;
			case R.id.title_right_iv:
				MainController.hideRedDot(mRedDotView);
				EventAgent.post(new QuotaEvent.PageJumpEvent(QuotaEvent.PageJumpEvent.QUOTA_JUMP_MESSAGE_PAGE, Constants.PAGE_NO_MAIN_ACTIVITY));
				break;
			case R.id.video_confirm_hint_iv:
				showOneBtnDialog(getString(R.string.video_verify_hint), getString(R.string.got_it));
				break;
			default:
				break;
		}
	}

	private void applyPermission() {
		if (PermissionsGrantedHelper.isSdkUnderM()) {
			if (PermissionsGrantedHelper.checkCameraPermission()) {
				CLog.i(TAG, "相机权限已打开");
				mGrantedCamera = true;
				judgeAutoJump();
			} else {
				mGrantedCamera = false;
				showNeedPermission(getString(R.string.camera_permission_hint, getString(R.string.app_name)));
			}
		} else {
			PermissionsGrantedHelper.PermissionsEachGranted(mRxPermissions, mGrantedListener, Manifest.permission.CAMERA);//摄像头权限
		}
		PermissionsGrantedHelper.PermissionsEachGranted(mRxPermissions, mGrantedListener, Manifest.permission.RECORD_AUDIO);//麦克风权限
	}

	private void judgeAutoJump(){
		if(mAutoJump && mGrantedCamera && mGrantedMicrophone){
			goToVideoVerify();
		}
	}

	private PermissionsGrantedHelper.PermissionsGrantedListener mGrantedListener = new PermissionsGrantedHelper.PermissionsGrantedListener() {
		@Override
		public void permissionsEachGrantedResult(Permission permission) {
			switch (permission.name) {
				case Manifest.permission.CAMERA:
					if (permission.granted) {
						mGrantedCamera = true;
						judgeAutoJump();
					} else {
						showNeedPermission(getString(R.string.camera_permission_hint, getString(R.string.app_name)));
					}
					break;
				case Manifest.permission.RECORD_AUDIO:
					if (permission.granted) {
						mGrantedMicrophone = true;
						judgeAutoJump();
					} else {
						showNeedPermission(getString(R.string.mic_permission_hint, getString(R.string.app_name)));
					}
					break;
				default:
					break;
			}
		}

		@Override
		public void PermissionsAllGrantedResult(boolean granted, int requestCode) {

		}
	};

	private void showNeedPermission(String tips){
		showTwoBtnDialog(tips, getString(R.string.go_to_settings), getString(R.string.cancel), new CommonDialog.ButtonClickListener() {
			@Override
			public void onCancel(CommonDialog dialog) {
				dialog.dismiss();
			}

			@Override
			public void onConfirm(CommonDialog dialog) {
				//忽略手势密码
				Global.setThirdPartyPageOpenedFlag(true);
				Global.NEED_REFRESH = false;
				Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
				intent.setData(Uri.parse("package:" + getActivity().getPackageName()));
				startActivity(intent);
				dialog.dismiss();
			}
		}, true);
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onRedDotShowEvent(QuotaEvent.ShowRedDotEvent event) {
		mRedDotView.setVisibility(View.VISIBLE);
	}

	private boolean notWorkTime() {
		long realTime = com.yyfax.infrastructure.Constants.getRealTime();
		Calendar calendar = Calendar.getInstance(Locale.CHINA);
		calendar.setTimeInMillis(realTime);
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		CLog.i(TAG, "time=" + dateFormat.format(realTime));
		//int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
		int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
		/*if(dayOfWeek == 1 || dayOfWeek == 7){
			return true;
		}*/
		if (hourOfDay < 9 || hourOfDay >= 18) {
			return true;
		}
		return false;
	}
}

